package com.songlanyun.modules.shareconfig.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.shareconfig.dao.SystemShareConfigDao;
import com.songlanyun.modules.shareconfig.entity.SystemShareConfig;
import com.songlanyun.modules.shareconfig.model.dto.SystemShareConfigDTO;
import com.songlanyun.modules.shareconfig.service.SystemShareConfigService;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("systemShareConfigService")
public class SystemShareConfigServiceImpl extends ServiceImpl<SystemShareConfigDao, SystemShareConfig>
        implements SystemShareConfigService {

    @Override
    public SystemShareConfig create(SystemShareConfig entity) {
        ValidatorUtils.validateEntity(entity);
        this.baseMapper.insert(entity);
        return entity;
    }

    @Override
    public SystemShareConfig modify(SystemShareConfig entity) {
        ValidatorUtils.validateEntity(entity);
        this.baseMapper.updateById(entity);
        return entity;
    }

    @Override
    public void remove(Integer id) {

    }


    @Override
    public SystemShareConfig set(Long shopId,SystemShareConfigDTO dto) {
        SystemShareConfig systemShareConfig = this.loadByShopId(shopId);
        if(systemShareConfig==null)
        {
            SystemShareConfig newConfig = mapSystemShareConfig(shopId, dto);
            return this.create(newConfig);
        }
        else
        {
            BeanUtil.copyPropertiesIgnoreNull(dto, systemShareConfig);
            return  this.modify(systemShareConfig);
        }

    }


    @Override
    public SystemShareConfig loadByShopId(Long shopId) {
        return this.getOne(
                new LambdaQueryWrapper<SystemShareConfig>()
                        .eq(SystemShareConfig::getShopId, shopId)
                        .last("limit 1"));
    }

    private SystemShareConfig mapSystemShareConfig(Long shopId,SystemShareConfigDTO dto) {
        SystemShareConfig entity = new SystemShareConfig();
        BeanUtil.copyPropertiesIgnoreNull(dto, entity);
        entity.setShopId(shopId);
        return entity;
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SystemShareConfig> page = this.page(
                new Query<SystemShareConfig>().getPage(params),
                new QueryWrapper<SystemShareConfig>()
        );
        return new PageUtils(page);
    }

}